/**
 * @file ext-link.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license MIT
 *
 */

const name = 'link'

const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}

export default {
  name,
  async init() {
    const svgEditor = this
    const { svgCanvas } = svgEditor
    const { ChangeElementCommand } = svgCanvas.history
    const addToHistory = (cmd) => { svgCanvas.undoMgr.addCommandToHistory(cmd) }
    const { $id, $click, $qq } = svgCanvas
    let selElems
    let started
    let newFO
    let p = {
      x:0,y:0,x1:0,y1:0
    }
    await loadExtensionTranslation(svgEditor)

    /**
     *
     * @param {string} attr attribute to change
     * @param {string|Float} val new value
     * @returns {void}
     */
    const setAttr = (attr, val) => {
      svgCanvas.changeSelectedAttribute(attr, val)
      svgCanvas.call('changed', selElems)
    }

    const createRect = (p)=>{
       newFO = svgCanvas.addSVGElementsFromJson({
        element: 'rect',
        attr: {
          x:p.x,
          y:p.y,
          width:0,
          height:0,
          class:'ems',
          'doc-type': 'link',
          id: svgCanvas.getNextId(),
          'stroke-width': 1,
          'fill':'none',
          'stroke':"gray",
          'stroke-dasharray':"5,5"
        }
      })
    }

    return {
      name: svgEditor.i18next.t(`${name}:name`),
      // The callback should be used to load the DOM with the appropriate UI items
      callback() {
        // Add the button and its handler(s)
        // Note: the star extension needs to be loaded before the polygon extension
        const fbtitle = `${name}:title`
        const titleStar = `${name}:buttons.0.title`
        const titlePolygon = `${name}:buttons.1.title`
        const buttonTemplate = `
              <se-button id="tool_link" title="${titlePolygon}" src="link.svg">
              </se-button>
          `
        svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), buttonTemplate, 2)

        $click($id('tool_link'), () => {
          if (this.leftPanel.updateLeftPanel('tool_link')) {
            svgCanvas.setMode('link')
          }
        })
      },
      mouseDown(opts) {
        if (svgCanvas.getMode() === 'link') {
          started = true
          p.x = opts.start_x
          p.y = opts.start_y
          createRect(p)
          return {
            started: true
          }
        }
        return undefined
      },
      mouseMove(opts) {
        if (!started) {
          return undefined
        }
        if (svgCanvas.getMode() === 'link') {
          const zoom = svgCanvas.getZoom()
          let x = opts.mouse_x/zoom
          let y = opts.mouse_y/zoom
          p.x1 = x
          p.y1 = y
          newFO.setAttribute("width",Math.abs(p.x1-p.x));
          newFO.setAttribute("height",Math.abs(p.y1-p.y));
          return {
            started: true
          }
        }
        return undefined
      },
      mouseUp() {
        if (svgCanvas.getMode() === 'link') {
          const keep = Math.abs(p.x1-p.x)>5 && Math.abs(p.y1-p.y)>5
          // svgCanvas.addToSelection([newFO], true);
          return {
            keep,
            element: newFO
          }
        }
        return undefined
      },

      updateLink(val){
        if(val.mode !== 'link'){
          return
        }
        const elem = svgCanvas.getSelectedElements()[0]
        elem.setAttribute("clink",val.data)
        // svgEditor.layersPanel.populateObjects()
        // addToHistory(new ChangeElementCommand(elem,{clink:val.data}))
        
      },
    }
  }
}
